var express = require('express');
var request = require('request')
var router = express.Router();
var mysqlUtils = require("../libs/MysqlUtils");

// https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code

// https://api.weixin.qq.com/sns/jscode2session?appid=wx31ee0a87b0f55d5e&secret=a6c32d885702c3887b7c5d12f6a82ff0&js_code=061mqjPt0s73Oa1viGOt0U76Pt0mqjPB&grant_type=authorization_code

// 密钥
// a6c32d885702c3887b7c5d12f6a82ff0

//

function guid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

router.post("/login", function (req, res) {
    //console.log(req);

    var url = 'https://api.weixin.qq.com/sns/jscode2session?appid=wx31ee0a87b0f55d5e&secret=a6c32d885702c3887b7c5d12f6a82ff0&js_code=:code&grant_type=authorization_code';
    url = url.replace(/:code/g, req.body.code);

    request(url, function (error, response, body) {
        if (!error && response.statusCode === 200) {
            var data = JSON.parse(body);
            if (data.openid) {
                console.log(data.openid);
                var openid = data.openid;

                mysqlUtils.query({
                    sql: "select * from user where openid=:openid",
                    params: {
                        openid: openid || ""
                    }
                }, function (err, rows) {
                    var uuid = guid();
                    if (rows.length === 1) {
                        mysqlUtils.query({
                            sql: "update user set openid=:openid, session=:session WHERE id=:id",
                            params: {
                                id: rows[0].id,
                                session: uuid,
                                openid: openid
                            }
                        }, function (err) {
                            if (!err) {
                                res.send({
                                    code: "000000",
                                    uuid: uuid
                                });
                            } else {
                                res.send({
                                    code: "200003",
                                    msg: '登录失败'
                                });
                            }
                        })
                    } else {
                        mysqlUtils.query({
                            sql: "insert into user(openid, session, name) values(:openid, :session, :name)",
                            params: {
                                openid: openid,
                                session: uuid,
                                name: req.body.name
                            }
                        }, function (err) {
                            if (!err) {
                                res.send({
                                    code: "000000",
                                    uuid: uuid
                                });
                            } else {
                                res.send({
                                    code: "200002",
                                    msg: '登录失败'
                                });
                            }

                        })
                    }
                })
            } else {
                res.send({
                    code: "200001",
                    msg: '登录失败'
                });
            }
        } else {
            res.send({
                code: "200000",
                msg: '登录失败'
            });
        }
    });
});

// session, id, isOpen=1
router.post("/query", function (req, res) {
        //console.log(req);
        if (req.body.session) {
            mysqlUtils.query({
                sql: "select * from user where session=:session",
                params: {
                    session: req.body.session
                }
            }, function (err, rows) {
                if (rows && rows.length === 1) {

                    // 重用接口
                    var sql = "select * from " +
                        "(select m.id id, m.name name, m.question question, ifnull(count, 0) count, ifnull(is_open, '0') is_open, ifnull(is_delete, '0') is_delete " +
                        "from mail m left join user_mail t on m.id=t.mid where m.name=:name) t "
                        + "where t.is_delete=0 ";
                    var param = {
                        name: rows[0].name
                    };

                    // id
                    if (req.body.id) {
                        sql += " and t.id=" + req.body.id;
                    }

                    // is_open
                    if (req.body.isOpen) {
                        sql += " and t.is_open=" + req.body.isOpen;
                    } else {
                        sql += " and t.is_open=0";
                    }

                    mysqlUtils.query({
                        sql: sql,
                        params: param
                    }, function (err, rows) {

                        if (rows) {
                            res.send({
                                code: '000000',
                                body: rows
                            });
                        } else {
                            res.send({
                                code: '000000',
                                body: []
                            });
                        }

                    })
                } else {
                    res.send({
                        code: "100000",
                        msg: "用户身份校验失败"
                    });
                }

            })
        } else {
            res.send({
                code: "100000",
                msg: "用户身份校验失败"
            });
        }
    }
);

router.post("/open", function (req, res) {
    if (req.body.session) {
        mysqlUtils.query({
            sql: "select * from user where session=:session",
            params: {
                session: req.body.session
            }
        }, function (err, users) {
            if (users && users.length === 1) {
                var sql = "select * from " +
                    "(select m.*, ifnull(count, 0) count, ifnull(is_open, '0') is_open, ifnull(is_delete, '0') is_delete " +
                    "from mail m left join user_mail t on t.mid=m.id where m.id=:id and name=:name) t " +
                    "where t.is_open=0 and is_delete=0";

                mysqlUtils.query({
                    // sql: "select m.id id, m.*, t.* from mail m left join user_mail t on t.mid=m.id where m.id=:id and name=:name",
                    sql: sql,
                    params: {
                        id: req.body.id,
                        name: users[0].name
                    }
                }, function (err, rows) {
                    if (rows && rows.length === 1 && rows[0].is_delete !== "1") {
                        var mail = rows[0];
                        var isRight = mail.answer === req.body.answer;
                        if (mail.count !== 0) {
                            if (isRight) {
                                mysqlUtils.query({
                                    sql: "update user_mail set count=:count, is_open='1' where mid=:mid and uid=:uid",
                                    params: {
                                        mid: rows[0].id,
                                        uid: users[0].id,
                                        count: mail.count + 1
                                    }
                                }, function (err) {
                                    if (err) {
                                        res.send({
                                            code: "200000",
                                            msg: "答案错误"
                                        });
                                    }
                                })
                            } else {
                                if (mail.count + 1 > 5) {
                                    console.log(mail.count + 1);
                                    mysqlUtils.query({
                                        sql: "update user_mail set is_delete='1' where mid=:mid and uid=:uid",
                                        params: {
                                            mid: rows[0].id,
                                            uid: users[0].id
                                        }
                                    }, function (err) {
                                        if (err) {
                                            res.send({
                                                code: "200000",
                                                msg: "答案错误"
                                            });
                                        }
                                    })
                                } else {
                                    mysqlUtils.query({
                                        sql: "update user_mail set count=:count where mid=:mid and uid=:uid",
                                        params: {
                                            mid: rows[0].id,
                                            uid: users[0].id,
                                            count: mail.count + 1
                                        }
                                    }, function (err) {
                                        if (err) {
                                            res.send({
                                                code: "200000",
                                                msg: "答案错误"
                                            });
                                        }
                                    })
                                }

                            }
                        } else {
                            var is_open = '0';
                            if (isRight) {
                                is_open = '1';
                            }
                            mysqlUtils.query({
                                sql: "insert into user_mail(uid, mid, count, is_open, is_delete) values(:uid, :mid, :count, :is_open, :is_delete)",
                                params: {
                                    uid: users[0].id,
                                    mid: rows[0].id,
                                    count: 1,
                                    is_open: is_open,
                                    is_delete: '0'
                                }
                            }, function (err) {
                                if (err) {
                                    res.send({
                                        code: "200000",
                                        msg: "答案错误"
                                    });
                                }
                            })
                        }

                        if (isRight) {
                            res.send({
                                code: "000000",
                                body: "答案正确"
                            });

                        } else {
                            res.send({
                                code: "200000",
                                msg: "答案错误"
                            });
                        }



                    } else {
                        res.send({
                            code: "200001",
                            msg: "未找到邮件"
                        });
                    }

                })
            } else {
                res.send({
                    code: "100000",
                    msg: "用户身份校验失败"
                });
            }

        })
    } else {
        res.send({
            code: "100000",
            msg: "用户身份校验失败"
        });
    }
});

router.post("/get", function (req, res) {
        //console.log(req);
        if (req.body.session) {
            mysqlUtils.query({
                sql: "select * from user where session=:session",
                params: {
                    session: req.body.session
                }
            }, function (err, rows) {
                if (rows && rows.length === 1) {

                    mysqlUtils.query({
                        sql: "select m.id, m.question, m.content from mail m, user_mail t " +
                        "where name=:name and t.mid=m.id and t.is_open='1' and m.id=:id",
                        params: {
                            id: req.body.id,
                            name: rows[0].name
                        }
                    }, function (err, rows) {
                        if (rows && rows.length > 0) {
                            res.send({
                                code: '000000',
                                body: rows[0]
                            });
                        } else {
                            res.send({
                                code: '200000',
                                msg: "未找到邮件"
                            });
                        }

                    })
                } else {
                    res.send({
                        code: "100000",
                        msg: "用户身份校验失败"
                    });
                }

            })
        } else {
            res.send({
                code: "100000",
                msg: "用户身份校验失败"
            });
        }
    }
);


router.post("/insert", function (req, res) {

    // data: {
    //     name: '1',
    //         question: '1',
    //         answer: '1',
    //         content: '1'
    // },

    //req.body.session

    if (req.body.session) {
        if (!req.body.name) {
            res.send({
                code: "200000",
                msg: "name 不能为空"
            });
        }

        if (!req.body.question) {
            res.send({
                code: "200000",
                msg: "question 不能为空"
            });
        }

        if (!req.body.answer) {
            res.send({
                code: "200000",
                msg: "answer 不能为空"
            });
        }

        if (!req.body.content) {
            res.send({
                code: "200000",
                msg: "content 不能为空"
            });
        }

        mysqlUtils.query({
            sql: "select * from user where session=:session",
            params: {
                session: req.body.session
            }
        }, function (err, rows) {
            if (rows && rows.length === 1) {
                mysqlUtils.query({
                    sql: "insert into mail(sender, name, question, answer, content) values(:sender, :name, :question, :answer, :content)",
                    params: {
                        sender: rows[0].openid,
                        name: req.body.name,
                        question: req.body.question,
                        answer: req.body.answer,
                        content: req.body.content
                    }
                }, function (err) {
                    if (err) {
                        res.send({
                            code: "200000",
                            msg: "发送失败"
                        });
                    } else {
                        res.send({
                            code: "000000",
                            msg: "发送成功"
                        });
                    }

                })
            } else {
                res.send({
                    code: "100000",
                    msg: "用户身份校验失败"
                });
            }
        });
    } else {
        res.send({
            code: "100000",
            msg: "用户身份校验失败"
        });
    }
});

module.exports = router;
